
var handlers = {
  
    init: function() {
        $(".dialog_opener").data('callback', "handlers.refresh");
        
        $(".content .delete_link").live('click', function(e) {
            e.preventDefault();
            
            if( !confirm("Delete Selected Record From System?") ) {
                return;
            }
            
            var $link = $(this);
            var url = $(this).attr("href");
            
            $.get(url, function() {
                $link.parents("tr").remove();
            });
        });
        
        $(".delete_selected").click(function(e) {
            e.preventDefault();
            
            handlers.deleteSelectedHandlers( $(this) );
        });
        
        this.setupGridBindings();
        this.setupSearchFields();
    },
    
    setupGridBindings: function() {
        $(".fullwidth tbody tr").click(function() {
            var url = $(this).data('url');
            
            $.get(url, function(data) {
                $(".details_block").html(data);
            });
        });
        
        $(".fullwidth tbody tr:first").click();
    },
    
    setupSearchFields: function() {
        $("#search_field").keyup(function(e) {
            
            if( e.keyCode == 13 ) {
                var url = $(this).data('url');
                var params = "field=" + $(this).val() + "&term=" + $("#search_by").val();
            
                $.post(url, params, function(data) {
                    $(".master_block").html(data);
                    handlers.setupGridBindings();
                });
            }
        });
    },
    
    refresh: function() {
        // force a page refresh
        window.history.go(0);
    },
    
    deleteSelectedHandlers: function($this) {
        var $inputs = $(".content table.fullwidth tbody tr input:checked");
            
        if( $inputs.length == 0 ) {
            alert("Please Select Handlers To Remove From System");
            return;
        }
            
        else {
            if( !confirm("Delete Selected Handlers and Related Data From System?") ) {
                return;
            }
        }
            
        var ids = [];
        $inputs.each(function() {
            ids.push( $(this).val() );
        });
            
        var query = "ids=" + ids;
        var url = $this.attr("href");
            
        $.post(url, query, function() {
                
            $inputs.each(function() {
                $(this).parents("tr").remove();
            });
        });
    }
};

$(document).ready(function() {
    handlers.init();
});
